<template>
  <div class="add-goods">
    <div class="add-form">
      <div class="form">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <p class="title">{{ $t("component.addGoods.1") }}</p>
          <el-form-item :label="$t('component.addGoods.2')" prop="name">
            <el-input type="text" v-model="form.name" :placeholder="$t('component.addGoods.3')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('component.addGoods.4')" prop="type">
            <el-cascader v-model="form.type" :options="typeList" :props="{ value: 'id', label: 'showName', children: 'categoryList' }" :placeholder="$t('component.addGoods.5')" @change="handleMultiTypeChange" style="width: 100%"></el-cascader>
          </el-form-item>
          <el-form-item v-for="item in typeParams" :label="item.typeParam.portugalName" :key="item.typeParam.id">
            <el-select v-model="item.typeParam.value" :placeholder="$t('component.addGoods.5')">
              <el-option v-for="meta in item.paramValues" :key="meta.id" :label="meta.portugalName" :value="meta.id"> </el-option>
            </el-select>
          </el-form-item>

          <p class="title">{{ $t("component.addGoods.1") }}</p>
          <el-form-item :label="$t('component.addGoods.6')" prop="des">
            <el-input type="textarea" maxlength="2000" show-word-limit :rows="6" v-model="form.des" :placeholder="$t('component.addGoods.7')"></el-input>
          </el-form-item>

          <p class="title">{{ $t("component.addGoods.1") }}</p>
          <el-row :gutter="20" type="flex" class="row-bg" justify="space-between">
            <el-col :span="16">
              <div class="grid-content bg-purple">
                <el-form-item :label="$t('component.addGoods.8')">
                  <el-col :span="10">
                    <el-button-group style="display: flex; align-items: center">
                      <el-button :type="form.dealType == 0 ? 'primary' : 'default'" @click="handleDealType(0)">{{ $t("component.addGoods.9") }}</el-button>
                      <el-button :type="form.dealType == 1 ? 'primary' : 'default'" @click="handleDealType(1)">{{ $t("component.addGoods.10") }}</el-button>
                    </el-button-group>
                  </el-col>
                  <el-col :span="12" :offset="2" v-if="form.dealType == 0">
                    <el-input :placeholder="$t('component.addGoods.11')" v-model="form.price">
                      <span slot="suffix" class="el-input__span">kz</span>
                    </el-input>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple-light">
                <el-form-item :label="$t('component.addGoods.12')">
                  <el-radio-group v-model="form.faceToFace">
                    <el-radio label="1">{{ $t("component.addGoods.13") }}</el-radio>
                    <el-radio label="0">{{ $t("component.addGoods.14") }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <p class="title">{{ $t("component.addGoods.1") }}</p>
          <el-form-item :label="$t('component.addGoods.15')" prop="imgList">
            <el-upload class="avatar-uploader" :action="uploadUrl" list-type="picture-card" :file-list="uploadList" :on-remove="handleRemove" :on-success="handleAvatarSuccess">
              <div class="avatar-add">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span class="avatar-uploader-tip">{{ $t("component.addGoods.35") }}</span>
              </div>
            </el-upload>
          </el-form-item>

          <p class="title">{{ $t("component.addGoods.1") }}</p>
          <el-form-item :label="$t('component.addGoods.16')" prop="telephone">
            <el-input type="text" v-model="form.telephone" :placeholder="$t('component.addGoods.17')"></el-input>
          </el-form-item>
          <el-form-item label="Caixa de correio" :prop="$t('component.addGoods.18')">
            <el-input type="text" v-model="form.email" :placeholder="$t('component.addGoods.19')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('component.addGoods.20')" prop="area">
            <el-cascader ref="area" v-model="form.area" :options="multiOptions" :props="{ value: 'code', label: 'name' }" :placeholder="$t('component.addGoods.21')" @change="handleMultiChange" style="width: 100%"></el-cascader>
          </el-form-item>
          <el-form-item :label="$t('component.addGoods.22')">
            <el-input type="text" v-model="form.address" :placeholder="$t('component.addGoods.23')"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="map" ref="map" style="width: 100%; height: 500px"></div>
          </el-form-item>
          <el-form-item class="text-center">
            <el-button type="default">{{ $t("component.addGoods.24") }}</el-button>
            <el-button type="primary" @click="handleSubmit">{{ $t("component.addGoods.25") }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Api from "@/api";
import { Domain, MAPKEY } from "@/constants";
import { isEmail } from "@/utils";
import { Loader } from "@googlemaps/js-api-loader";
export default {
  name: "AddGoods",
  props: {
    goods: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      domain: Domain,
      uploadUrl: Api.uploadUrl,
      map: null,
      form: {
        name: "",
        type: "",
        area: "",
        des: "",
        price: "",
        imgList: "",
        telephone: "",
        email: "",
        address: "",
        faceToFace: 0,
        dealType: 0,
        latitude: "",
        longitude: "",
        areaName: "",
        parameterList: "",
      },
      rules: {
        avatar: { required: true, message: window.$lang.t("component.addGoods.26"), trigger: "change" },
        name: { required: true, message: window.$lang.t("component.addGoods.27"), trigger: "blur" },
        des: { required: true, message: window.$lang.t("component.addGoods.28"), trigger: "blur" },
        telephone: { required: true, message: window.$lang.t("component.addGoods.29"), trigger: "blur" },
        email: [
          { required: true, message: window.$lang.t("component.addGoods.30"), trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!isEmail(value)) {
                callback(new Error(window.$lang.t("component.addGoods.31")));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        type: { required: true, message: window.$lang.t("component.addGoods.32"), trigger: "change" },
        area: { required: true, message: window.$lang.t("component.addGoods.33"), trigger: "change" },
      },
      typeParams: [],
      paramsValue: [],
      multiOptions: [],
      typeList: [],
      uploadList: [],
    };
  },
  created() {
    this.loadTree();
    this.loadType();

    if (this.goods.id) {
      this.form = this.goods;
      this.form.area = this.goods.areaCode.split("/");
      this.form.type = [this.goods.sectionId, this.goods.categoryId];
      const imgs = JSON.parse(this.goods.imgList);
      this.uploadList = imgs.map((item) => {
        return {
          path: item,
          url: Domain + item,
        };
      });
    } else {
      this.loadUserInfo();
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      const mapLoader = new Loader({
        apiKey: MAPKEY,
        version: "weekly",
      });
      mapLoader.load().then(async () => {
        const position = await this.getPosition();
        this.map = new window.google.maps.Map(this.$refs.map, {
          center: position,
          zoom: 8,
        });
        let marker = null;
        this.map.addListener("click", (mapsMouseEvent) => {
          if (marker) {
            marker.setMap(null);
          }
          this.form.latitude = mapsMouseEvent.latLng.lat();
          this.form.longitude = mapsMouseEvent.latLng.lng();
          marker = new window.google.maps.Marker({
            position: mapsMouseEvent.latLng,
            map: this.map,
          });
        });
      });
    },
    getPosition() {
      return new Promise((resolve) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const { latitude, longitude } = position.coords;
              resolve({
                lat: latitude,
                lng: longitude,
              });
            },
            () => {
              resolve({
                lat: 0,
                lng: 0,
              });
            }
          );
        } else {
          resolve({
            lat: 0,
            lng: 0,
          });
        }
      });
    },
    loadUserInfo() {
      Api.loadUser().then((res) => {
        this.form.email = res.email;
        this.form.telephone = res.mobile;
      });
    },
    handleAvatarSuccess(response, file, fileList) {
      this.uploadList.push({
        path: response.path,
        url: Domain + response.path,
      });
    },
    handleRemove(file, fileList) {
      const index = this.uploadList.findIndex((item) => item.path === file.path);
      this.uploadList.splice(index, 1);
    },
    handleMultiChange(value) {
      // const address = this.$refs.area.getCheckedNodes()[0].pathLabels.join('');
      this.form.area = value;
      this.form.areaName = this.$refs.area.getCheckedNodes()[0].pathLabels.join("/");
      // 逆地理位置解析
      // axios({
      //   url: 'https://maps.googleapis.com/maps/api/geocode/json',
      //   method: 'get',
      //   params: {
      //     address: address,
      //     key: MAPKEY,
      //   },
      // }).then((res) => {
      //   if (res.status === 200) {
      //     const { status, results, error_message } = res.data;
      //     if (status === 'OK') {
      //       this.form.latitude = results[0].geometry.location.lat;
      //       this.form.longitude = results[0].geometry.location.lng;
      //     } else {
      //       console.log(error_message);
      //     }
      //   }
      // });
    },
    handleMultiTypeChange(value) {
      this.form.type = value;
      Api.typeParamsList({ typeId: value[1] }).then((res) => {
        this.typeParams = res;
      });
      // TODO 查询下级参数
    },
    handleDealType(type) {
      this.form.dealType = type;
    },
    loadTree() {
      Api.areaTree().then((res) => {
        this.multiOptions = res;
      });
    },
    loadType() {
      Api.goodsTypeList().then((res) => {
        this.typeList = res;
      });
    },
    handleSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.areaCode = "/" + this.form.area.join("/") + "/";
          const section = this.typeList.find((item) => item.id == this.form.type[0]);
          this.form.sectionId = section.id;
          this.form.sectionName = section.showName;
          const category = section.categoryList.find((item) => item.id == this.form.type[1]);
          this.form.categoryId = category.id;
          this.form.categoryName = category.showName;
          if (this.typeParams.length > 0) {
            this.form.parameterList = JSON.stringify(this.typeParams);
          }
          const params = {
            ...this.form,
            imgList: JSON.stringify(this.uploadList.map((item) => item.path)),
            area: "",
            type: "",
          };
          Api.addGoods(params).then(() => {
            this.$emit("success");
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
/* form */
.add-form {
  background: #fff;
  border-radius: 4px;
  .title {
    color: #333;
    font-weight: bold;
    font-size: 16px;
    padding-left: 150px;
    margin-bottom: 20px;
    padding-top: 20px;
    border-top: 1px dashed #e8e8e8;
    margin-top: 40px;
  }
  .form {
    width: 80%;
    margin: auto;
  }
}
.avatar-uploader {
  ::v-deep .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    .avatar-add {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
      }
      .avatar-uploader-tip {
        color: #999;
        font-size: 12px;
        line-height: 1.5;
      }
    }

    .avatar {
      width: 120px;
      height: 120px;
      display: block;
    }
  }
}
</style>
